package com.generator.persistence.support;

import com.generator.config.ServiceConfig;
import com.generator.constant.NodePath;
import com.generator.persistence.EpochPersistence;
import com.generator.service.ZkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ZkEpochPersistence implements EpochPersistence, InitializingBean {

    @Autowired
    private ZkService zkService;

    @Autowired
    private ServiceConfig serviceConfig;

    private String nodePath;

    @Override
    public long loadEpoch() {
        String val = zkService.getData(nodePath);
        return Long.valueOf(val);
    }

    @Override
    public boolean upgradeEpoch(long newEpoch) {
        return zkService.setData(nodePath,newEpoch+"");
    }

    @Override
    public void afterPropertiesSet() {
        nodePath = NodePath.EPOCH_PATH + "/" + serviceConfig.getWorkerId();

        boolean exists = zkService.exists(nodePath);

        long epoch = 0;

        if(!exists) {
            zkService.createPath(nodePath,(epoch+1)+"", CreateMode.PERSISTENT);
            log.info("[ZkEpochPersistence] 初始化 >>> 使用{}初始化节点:{}的值",1);
        } else {

            String val = zkService.getData(nodePath);
            if(StringUtils.isNotBlank(val)) {
                epoch = Long.valueOf(val);
            }

            zkService.setData(nodePath,(epoch+1)+"");

            log.info("[ZkEpochPersistence] 初始化 >>> oldEpoch:{},newEpoch:{}",epoch,epoch+1);
        }
    }
}
